package com.swust.excel.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class WordExportController {

    @GetMapping("/exportWord")
    public void exportWord(HttpServletResponse response) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("reportName", "ask for advance of payment");

        LoopRowTableRenderPolicy loopRowTableRenderPolicy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .buildGramer("${", "}")//此处可以变更原模板${}
                .bind("yc", loopRowTableRenderPolicy)//标记表格参数
                .bind("hl", loopRowTableRenderPolicy)//标记表格参数
                .bind("ys", loopRowTableRenderPolicy)//标记表格参数
                .build();

        ClassPathResource classPathResource = new ClassPathResource(File.separator + "templates" + File.separator + "trace-analysis-report-template.docx");
        try (InputStream fileInputStream = classPathResource.getInputStream();
             XWPFTemplate template = XWPFTemplate.compile(fileInputStream, config)
                     .render(resultMap);
        ) {
            response.setContentType("application/vnd.ms-word");
            response.setCharacterEncoding("utf-8");
            String fileName = "污染源溯源分析报告";
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".doc");
            template.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("污染源溯源分析报告导出失败!", e);
        }
    }
}
